package com.example.usbfileutils.bylibaums

import android.util.Log
import me.jahnen.libaums.core.fs.FileSystem
import me.jahnen.libaums.core.fs.UsbFile
import me.jahnen.libaums.core.fs.UsbFileStreamFactory.createBufferedOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.io.OutputStream
import java.util.concurrent.CountDownLatch

class FileCopyTaskByLibaums(
    val srcFile: File, val currentUsbDir: UsbFile, val curFileSystem: FileSystem
) : Runnable {

    var countDownLatch: CountDownLatch? = null

    companion object {
        private val TAG = "FileCopyTask"
    }

    override fun run() {

        try {

            Log.d(TAG, "start copy file ${srcFile.name} to " + currentUsbDir.absolutePath)

            val usbFile = currentUsbDir.createFile(srcFile.name)

            val size = srcFile.length()
            usbFile.length = srcFile.length()
            val inputStream = FileInputStream(srcFile)
            val outputStream: OutputStream = createBufferedOutputStream(usbFile, curFileSystem)
            val bytes = ByteArray(1337)
            var count: Int
            var total: Long = 0
            while (inputStream!!.read(bytes).also { count = it } != -1) {
                outputStream.write(bytes, 0, count)
                if (size > 0) {
                    total += count.toLong()
                    var progress = total.toInt()
                    if (srcFile.length() > Int.MAX_VALUE) {
                        progress = (total / 1024).toInt()
                    }

                    Log.d(TAG, "copy file : $progress")
                }

            }
            outputStream.close()
            inputStream.close()
            usbFile.close()

            Log.d(TAG, "copy file ${srcFile.name} to ${usbFile.absolutePath} successfully")

        } catch (e: IOException) {
            Log.e(TAG, "error copying! ${srcFile.absolutePath}", e)
        } finally {
            countDownLatch?.countDown()
        }
    }
}